package com.qxzn.app.page.model;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.util.DownloadBroadcast;
import com.qxzn.app.bean.LatestVersionBean;
import com.qxzn.app.page.interfaces.MyInterface;
import com.qxzn.app.page.view.MyDialog;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.DateUtil;
import com.qxzn.app.util.FileUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.app.util.SystemUtil;

import java.io.File;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UpdateVersionModel {

    private Activity activity;
    private MyInterface.OnUpdateVersionListener listener;
    private File apkPathFile;
    private MyDialog dialog;
    private DownloadBroadcast mDownloadBroadcast;

    public UpdateVersionModel(Activity activity, MyInterface.OnUpdateVersionListener listener) {
        this.activity = activity;
        this.listener = listener;
    }

    public void getUpdateVersionInfo(boolean showDialog) {
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), "{\"type\":\"2\"}");
        Call<LatestVersionBean> call = HttpRequest.getService().checkLatestVersion(body);
        call.enqueue(new Callback<LatestVersionBean>() {
            @Override
            public void onResponse(Call<LatestVersionBean> call, Response<LatestVersionBean> response) {
                LatestVersionBean bean = response.body();
                if (bean != null && bean.getCode() == 200 && bean.getData() != null) {
                    LatestVersionBean.DataBean data = bean.getData();
                    if (TextUtils.equals(activity.getClass().getSimpleName(), "VersionUpdateActivity")) {
                        if (!TextUtils.equals(AppUtil.getVersionName(activity), data.getNumber())) {
                            if (showDialog) {
                                showUpdateDialog(data);
                            }
                            if (listener != null) {
                                listener.onGetUpdateInfoSuccess(data);
                            }
                        } else {
                            if (TextUtils.equals(activity.getClass().getSimpleName(), "VersionUpdateActivity")) {
                                AppUtil.showToast(activity, "已是最新版本");
                            }
                        }
                    } else {
                        if (!TextUtils.equals(AppUtil.getVersionName(activity), data.getNumber())) {
                            if (!TextUtils.equals(DateUtil.formMillisToStr(System.currentTimeMillis(), DateUtil.yearToDatePattern), SharePreferenceUtil.getNoticeUpdateDate(activity))) {
                                showUpdateDialog(data);
                            }
                            if (listener != null) {
                                listener.onGetUpdateInfoSuccess(data);
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<LatestVersionBean> call, Throwable t) {
                if (listener != null) {
                    listener.onGetUpdateInfoFailure();
                }
            }
        });
    }

    private void showUpdateDialog(LatestVersionBean.DataBean data) {
        dialog = new MyDialog.Builder(activity).setWidth(Math.round(SystemUtil.getScreenWidth(activity) * 0.8f)).setHeight(Math.round(SystemUtil.getScreenHeight(activity) * 0.8f))
                .setTitle("版本更新").setMessage(data.getContent()).setCancelAble(false).setCanceledOnTouchOutside(false)
                .setNegativeButtonText("下次再说").setNegativeButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (TextUtils.equals(activity.getClass().getSimpleName(), "MainActivity")) {
                            SharePreferenceUtil.setNoticeUpdateDate(activity, DateUtil.formMillisToStr(System.currentTimeMillis(), DateUtil.yearToDatePattern));
                        }
                        dialog.dismiss();
                    }
                }).setPositiveButtonText("立即升级").setPositiveButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        apkPathFile = new File(FileUtil.getBaseApkPath(activity) + File.separator + "小π_desktop_v" + data.getNumber() + ".apk");
                        if (apkPathFile != null && apkPathFile.exists()) {
                            install();
                        } else {
//                            downLoadFile();
                            mDownloadBroadcast = new DownloadBroadcast();
                            mDownloadBroadcast.setDownLoadFile(apkPathFile);
                            HttpRequest.downloadFile(activity, "版本更新下载", HttpRequest.BASE_URL + "api/edition/edition_down?type=2", "apk", "小π_desktop_v" + data.getNumber() + ".apk", mDownloadBroadcast);
                        }
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    private void install() {
        Intent intent1 = new Intent(Intent.ACTION_VIEW);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri1 = FileProvider.getUriForFile(activity, Constant.authority, apkPathFile);
            intent1.setDataAndType(uri1, "application/vnd.android.package-archive");
        } else {
            intent1.setDataAndType(Uri.fromFile(apkPathFile), "application/vnd.android.package-archive");
        }
        AppUtil.showLog("apk file:" + apkPathFile);
        try {
            activity.startActivity(intent1);
        } catch (Exception e) {
            AppUtil.showLog("安装启动异常:" + e);
            e.printStackTrace();
        }
    }

    public void removeListener() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
        if (mDownloadBroadcast != null) {
            activity.unregisterReceiver(mDownloadBroadcast);
        }
        listener = null;
    }
}
